<?php

namespace app\data\controller\record;

use app\admin\service\WxWorkService;
use app\data\service\CityUserRelationService;
use app\data\service\RecordService;
use app\data\service\ReworkService;
use app\data\service\StringParse;
use think\admin\Controller;
use think\admin\service\AdminService;
use think\facade\Cache;

/**
 * 备注记录
 * Class CarRecordOperate
 * @package app\data\controller\user
 */
class CarRecordRemark extends Controller
{
    /**
     * 备注记录
     * @auth
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        // 设置页面标题
        $this->title = '备注记录';
        // 创建查询对象
        $this->_query('data_record_remark_log')->order('id desc')->where('record_id', $this->request->request('record_id'))->page(false);
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _page_filter(array &$data)
    {
        $adminIds = array_column($data, 'admin_id');
        $workUsers = $this->app->db->name('work_user')->whereIn('id', $adminIds)->select()->toArray();
        foreach ($workUsers as $workUser) {
            $userId2Name[$workUser['id']] = $workUser['name'];
        }

        foreach ($data as &$item) {
            $item['admin_name'] = $userId2Name[$item['admin_id']] ?? '';
        }
    }

    /**
     * 备注
     * @auth
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function remark()
    {
        if ($this->request->isGet()) {

            $this->analyzeReasons = RecordService::instance()->analyzeReasons();
            $this->analyze_reason = $this->request->request('analyze_reason');
            $this->record_id = $this->request->request('record_id');

            $this->fetch('remark');
        } else {
            $data = $this->_vali([
                'record_id.require' => '不能为空',
                'analyze_reason.require' => '不能为空',
                'need_remind.require' => '不能为空',
                'remark.default' => '',
                'remind_at.default' => null,
                'admin_id.value' => AdminService::instance()->getUserId(),
            ]);

            $record = $this->app->db->name('data_record')->where('id', $data['record_id'])->findOrEmpty();
            if (!$record) {
                $this->error('查无该记录信息');
            }

            $this->app->db->name('data_record_remark_log')->insert($data);
            $this->app->db->name('data_record')->where('id', $data['record_id'])->update(['analyze_reason' => $data['analyze_reason']]);

            $this->success('备注成功');
        }
    }
}